package com.xncoding.jwt.controller;

import com.xncoding.jwt.config.sse.PayCompletedEvent;
import com.xncoding.jwt.config.sse.PayCompletedListener;
import com.xncoding.jwt.config.swagger.SwaggerTagConst;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * push 支付等待
 * pay-callback 支付完成
     客户端向后台(SseController->push)发送异步请求，客户端处于监听等待状态;
     微信(支付宝)支付成功后回调后台(SseController->payCallback模拟);
     payCallback方法通过applicationContext.publishEvent向系统内部发送支付完成事件;
     push方法通过payCompletedListener监听事件并通过SseEmitter发送给客户端。
     名词解释：SSE–server send event是一种服务端推送的技术，本例使用SseEmitter来实现。
 * @author Dibbing Pan
 * @date 2019/8/28
 */
@Api(tags =  SwaggerTagConst.SSE.sse, value = "sever send event", description = "服务端主动推送")
@RestController
public class SseController {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private PayCompletedListener payCompletedListener;

    @GetMapping
    @ResponseBody
    public String res(){
        return "sssss";
    }

    @GetMapping("/push")
    public SseEmitter push(@RequestParam Long payRecordId){
        final SseEmitter emitter = new SseEmitter();
        try {
            payCompletedListener.addSseEmitters(payRecordId,emitter);
        }catch (Exception e){
            emitter.completeWithError(e);
        }

        return emitter;
    }

    @GetMapping("/pay-callback")
    public String payCallback(@RequestParam Long payRecordId){
        applicationContext.publishEvent(new PayCompletedEvent(this,payRecordId));
        return "请到监听处查看消息";
    }

}
